<template>
  <div class="app-container">
    <div class="filter-container">

      <el-input v-model="searchObj.data.role_name" size="medium" placeholder="角色名称" class="global-search-box"/>
      <el-button type="primary" size="medium" icon="el-icon-search" @click="getRoles()">搜索</el-button>
      <el-button type="primary" size="medium" @click="reset()">重置</el-button>

      <span class="filter-container-right">
        <el-button v-permission= "{ permissionCode: 'role:add' }" type="primary" size="medium" icon="el-icon-plus" @click="addRole">新增</el-button>
        <el-button v-permission= "{ permissionCode: 'role:delete' }" type="danger" size="medium" icon="el-icon-close" @click="deleteRoles">删除</el-button>
      </span>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      border
      highlight-current-row
      @selection-change="handleSelectChange">
      <el-table-column type="selection" width="40"/>
      <el-table-column align="center" label="角色名称" prop="role_name" min-width="150"/>
      <el-table-column align="center" label="角色描述" prop="description" min-width="120"/>
      <el-table-column align="center" label="权重" prop="priority" min-width="160"/>
      <el-table-column align="center" label="创建人" prop="create_user" min-width="100"/>
      <el-table-column align="center" label="修改人" prop="modify_user" min-width="100"/>
      <el-table-column align="center" label="创建日期" prop="create_date" min-width="160"/>
      <el-table-column align="center" label="修改日期" prop="modify_date" min-width="160"/>
      <el-table-column align="center" label="操作" min-width="280">
        <template slot-scope="scope">
          <el-button v-permission= "{ permissionCode: 'role:resource' }" type="success" size="mini" @click="SelectResources(scope.row)">分配资源</el-button>
          <el-button v-permission= "{ permissionCode: 'role:update' }" type="primary" size="mini" icon="el-icon-edit" @click="editRole(scope.row)">修改</el-button>
          <el-button v-permission= "{ permissionCode: 'role:delete' }" type="danger" size="mini" icon="el-icon-delete" @click="deleteRole(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title=" isEdit ? '编辑资源' : '新增资源'" :visible.sync="FormVisible" width="600px">
      <el-form ref="ruleForm" :model="roleForm" :rules="rules" >
        <el-form-item :label-width="formLabelWidth" label="角色名称" prop="role_name">
          <el-input v-model="roleForm.role_name" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="权重" prop="priority">
          <el-input v-model.number="roleForm.priority" auto-complete="off"/>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" auto-complete="off"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAdd()">取 消</el-button>
        <el-button type="primary" @click="isEdit ? confirmEditRole('ruleForm') : confirmAddRole('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <div class="global-paging">
      <el-pagination
        :page-size="10"
        :total="total"
        :page-sizes="[10, 20, 40]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="分配资源与权限" width="500px" @close="cancel">
      <el-row>
        <el-col :span="12">
          <h3 style="text-align: center">资源</h3>
          <el-tree
            ref="resourceTree"
            :data="resources"
            :default-checked-keys="roleResources.resources"
            :props="defaultProps"
            :expand-on-click-node="false"
            :check-strictly="true"
            show-checkbox
            default-expand-all
            node-key="id"
            @node-click="nodeClick"/>
        </el-col>
        <el-col :span="12">
          <h3 style="text-align: center">权限</h3>
          <el-checkbox-group v-model="roleResources.permissions">
            <el-checkbox v-for="per in allPermissions" :key="per.id" :label="per.id" style="display: block;margin-left: 60px;">{{ per.name }}</el-checkbox>
          </el-checkbox-group>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="confirmSelectResource()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'

export default {
  name: 'RoleList',
  data() {
    return {
      dialogFormVisible: false,
      FormVisible: false,
      isEdit: false,
      list: null,
      listLoading: false,
      total: null,
      rules: {
        role_name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请输入权重', trigger: 'blur' },
          { type: 'number', message: '权限值必须为数字' }
        ]
      },
      delRoleIds: [],
      formLabelWidth: '120px',
      roleResources: {
        resources: [],
        permissions: [],
        role_id: null
      },
      resources: [],
      searchObj: {
        currentNo: 1,
        pageSize: 10,
        data: {
          role_name: '',
          isAdmin: null,
          beginTime: null,
          endTime: null
        }
      },
      roleForm: {},
      copyRoleForm: {}, // 修改取消时使用
      defaultProps: {
        children: 'nodes',
        label: 'text'
      },
      allPermissions: []
    }
  },
  created() {
    this.getRoles()
  },
  methods: {
    nodeClick(data, node) {
      this.allPermissions = data.permissions
    },
    SelectResources(row) {
      this.dialogFormVisible = true
      this.roleResources.role_id = row.id
      commonApi('/auth/resources', 'post', { role_id: row.id }).then(response => {
        if (response.code === 1) {
          this.resources = response.data
          this.dataTranslation(response.data)
        }
      })
    },
    dataTranslation(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].hasResource === 1) {
          this.roleResources.resources.push(data[i].id)
        }
        if (data[i].permissions && data[i].permissions.length > 0) {
          for (let j = 0; j < data[i].permissions.length; j++) {
            if (data[i].permissions[j].hasPermission) {
              this.roleResources.permissions.push(data[i].permissions[j].id)
            }
          }
        }
        if (data[i].nodes) {
          this.dataTranslation(data[i].nodes)
        }
      }
    },
    confirmSelectResource() {
      this.roleResources.resources = this.$refs['resourceTree'].getCheckedKeys()
      commonApi('/auth/addResourceForRole', 'post', this.roleResources).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '资源分配成功',
            type: 'success'
          })
          this.cancel()
        }
      })
    },
    cancel() {
      this.dialogFormVisible = false
      this.roleResources.permissions = []
      this.roleResources.resources = []
      this.roleResources.role_id = null
    },
    handleCurrentChange(val) {
      this.searchObj.currentNo = val
      this.getRoles()
    },
    handleSizeChange(val) {
      this.searchObj.pageSize = val
      this.getRoles()
    },
    getRoles() {
      this.listLoading = true
      commonApi('/auth/pages', 'post', this.searchObj).then(response => {
        if (response.code === 1) {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    reset() {
      for (const index in this.searchObj.data) {
        this.searchObj.data[index] = null
      }
      this.getRoles()
    },
    handleSelectChange(valArr) {
      this.delRoleIds = []
      for (let i = 0; i < valArr.length; i++) {
        this.delRoleIds.push(valArr[i].id)
      }
    },
    addRole() {
      this.isEdit = false
      this.FormVisible = true
    },
    confirmAddRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/auth/addRole', 'post', this.roleForm).then(response => {
            if (response.code === 1) {
              this.roleForm = {}
              this.listLoading = false
              this.getRoles()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancelAdd() {
      this.FormVisible = false
      if (!this.isEdit) {
        for (const index in this.roleForm) {
          this.roleForm[index] = null
        }
      } else {
        this.roleForm = this.copyRoleForm
      }
    },
    deleteRole(row) {
      this.$confirm(`确定要删除角色：${row.role_name} ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.delRoleIds.push(row.id)
        this.deleteRolesInterim()
      }).catch(() => {
      })
    },
    deleteRoles() {
      if (this.delRoleIds.length === 0) {
        this.$message({
          message: '请选择需要删除角色 ！',
          type: 'error'
        })
        return
      }
      this.$confirm(`确定要批量删除角色 ?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.deleteRolesInterim()
      }).catch(() => {
      })
    },
    deleteRolesInterim() {
      this.listLoading = true
      commonApi('/auth/remove', 'post', this.delRoleIds).then(response => {
        if (response.code === 1) {
          this.$message({
            message: '角色删除完成',
            type: 'success'
          })
          this.listLoading = false
          this.delRoleIds = []
          this.getRoles()
        }
      }).catch(() => {
        this.listLoading = false
      })
    },
    editRole(row = {}) {
      this.FormVisible = true
      this.isEdit = true
      this.roleForm = row
      this.copyRoleForm = row
    },
    confirmEditRole(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.FormVisible = false
          this.listLoading = true
          commonApi('/auth/updateRole', 'post', this.roleForm).then(response => {
            if (response.code === 1) {
              this.roleForm = {}
              this.listLoading = false
              this.getRoles()
            }
          }).catch(() => {
            this.listLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss">
</style>
